<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataParams.id ? '编辑' : '新增'}-生产投料`"
		width="900px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		append-to-body
		:permission-prefix="permissionPrefix"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<el-row ref="box1">
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="产线" prop="productionLineId">
						<jk-select v-model="ruleForm.productionLineId" size="medium" class="width-100-percent" :option-list="productionLineList" value-key-name="id" label-key-name="name" placeholder="产线" @change="onPrdLineChange"></jk-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="品种" prop="productId">
						<remote-search-product-input
							placeholder="品种"
							only-key="productId"
							query-name="productName"
							:form-data="ruleForm"
							@on-select="onSelectProductChange"
						></remote-search-product-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="批号">
						<remote-search-batch-code-input
							:disabled="!ruleForm.productId"
							placeholder="批号"
							only-key="batchId"
							query-name="batchCode"
							:form-data="ruleForm"
							@on-select="onSelectBatchChange"
						></remote-search-batch-code-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="投料重量" prop="totalWeight">
						<jk-number-input v-model="ruleForm.totalWeight" clearable placeholder="投料重量" class="width-100-percent" />
					</el-form-item>
				</el-col>
				<!--<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="投料日期" prop="billDate">
						<jk-date-picker v-model="ruleForm.billDate" type="date" size="medium" placeholder="投料日期" />
					</el-form-item>
				</el-col>-->
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="投料时间" prop="feedstockDateTime">
						<jk-date-picker v-model="ruleForm.feedstockDateTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" size="medium" placeholder="投料时间" @change="onDateTimeChange" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="投料班次">
						<span class="read-only-2">{{ ruleForm.scheduleShiftName }}</span>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="区域">
						<span class="read-only-2">{{ ruleForm.workshopName }}</span>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item class="margin-bottom-10" label="投料人" prop="empList">
						<div v-if="!ruleForm.empList.length" class="link-style text-ellipsis" @click="checkboxEmpDialogState = true">{{ ruleForm.empList.length ? ruleForm.empList.map(x => x.name).join(' , ') : '点击选择' }}</div>
						<div v-else>
							<div style="max-height: 300px;overflow: auto;display: flex;flex-wrap: wrap;">
								<div
									v-for="(item, index) in ruleForm.empList"
									:key="item.id"
									style="width: calc(100% / 6);box-sizing: border-box;padding: 2px;cursor: pointer;"
								>
									<el-tag class="width-100-percent flex-between-center" closable @close="ruleForm.empList.splice(index, 1)">
										<div>
											<span class="el-icon-user item-gap"></span>
											<span>{{ item.name }}</span>
										</div>
									</el-tag>
								</div>
								<div style="box-sizing: border-box;padding: 2px;cursor: pointer;">
									<el-tag type="info" effect="plain" class="width-100-percent flex-between-center el-icon-plus" @click="checkboxEmpDialogState = true">添加</el-tag>
								</div>
							</div>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item class="margin-bottom-10" label="备注">
						<el-input v-model="ruleForm.remark" type="textarea" :rows="1" placeholder="" />
					</el-form-item>
				</el-col>
			</el-row>

		</el-form>
		<checkbox-emp-dialog
			:default-select-rows="ruleForm.empList"
			check-key-name="id"
			:dialog-state="checkboxEmpDialogState"
			@on-visible-change="onVisibleChangeOfCheckboxEmpDialog"
			@on-confirm="onConfirmBtnOfCheckboxEmpDialog"
		></checkbox-emp-dialog>
		<checkbox-product-dialog
			:default-select-rows="ruleForm.productList"
			default-stock-type="RAW_MATERIAL"
			check-key-name="productId"
			:dialog-state="selectProductDialogState"
			@on-confirm="onConfirmBtnOfSelectProductDialog"
			@on-visible-change="onVisibleChangeOfSelectProductDialog"
		></checkbox-product-dialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        productionFeedstockCreate,
        productionFeedstockUpdate,
        productionFeedstockGet
    } from '../../../api/production/feedMaterial';
    import { formatDate, formatTime, tipsBar } from '../../../utils/jk/jk-tool';
    import {
        productionPrdNoticeMachineChangeGet
    } from '../../../api/production/xsRenovateOrder';
    import { workforcemanagementScheduleList } from '../../../api/schedule/scheduling';
    import checkboxEmpDialog from '../../personnel/group/checkbox-emp-dialog';
    import { cottonPpfCottonBlendingGet } from '../../../api/production/productConfigCotton';
    import remoteSearchProductInput from '../../production/order/components/remote-search-product-input';
    import remoteSearchBatchCodeInput from '../../production/qhPrd/productConfigCotton/components/remote-search-batch-code-input';
    import { ppfProductionLinePage } from '../../../api/production/produtionLine';
    import { validateArr } from '../../../utils/jk/validator';
    import checkboxProductDialog from '../../production/order/components/checkbox-product-dialog';
    import { workforcemanagementScheduleShiftByTime } from '../../../api/schedule/empReplacePost';
    export default {
        components: {
            checkboxProductDialog,
            remoteSearchBatchCodeInput,
            remoteSearchProductInput,
            checkboxEmpDialog },
        name: '',
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataParams: {
                type: Object,
                default() {
                    return {};
                }
            }
        },
        mixins: [calHeight],
        data() {
            return {
                selectProductDialogState: false,
                checkboxEmpDialogState: false,
                productionLineList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    'feedstockDateTime': '',
                    'batchCode': '',
                    'batchId': null,
                    'billDate': '',
                    'code': '系统自动生成',
                    'empList': [],
                    'ppfCottonBlendingCode': '',
                    'ppfCottonBlendingId': null,
                    'prdNoticeCode': '',
                    'prdNoticeId': null,
                    'productCode': '',
                    'productId': null,
                    'productList': [],
                    'productModels': '',
                    'productName': '',
                    'productionLineCode': '',
                    'productionLineId': null,
                    'productionLineName': '',
                    'remark': '',
                    'scheduleShiftId': null,
                    'shiftCode': '',
                    'shiftId': null,
                    'shiftName': '',
                    'totalQty': null,
                    'totalWeight': null,
                    'unitCode': '',
                    'unitId': null,
                    'unitName': '',
                    'workshopCode': '',
                    'workshopId': null,
                    'workshopName': ''
                },
                rules: {
                    empList: [{ required: true, validator: validateArr, trigger: 'change' }],
                    ppfCottonBlendingId: [{ required: true, trigger: 'change' }],
                    feedstockDateTime: [{ required: true, trigger: 'change' }],
                    productionLineId: [{ required: true, trigger: 'change' }],
                    scheduleShiftId: [{ required: true, trigger: 'change' }],
                    billDate: [{ required: true, trigger: 'change' }],
                    totalWeight: [{ required: true, trigger: 'change' }],
                    workshopId: [{ required: true, trigger: 'change' }],
                    productId: [{ required: true, trigger: 'change' }],
                    batchId: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onVisibleChangeOfSelectProductDialog(e) {
                this.selectProductDialogState = e;
            },
            onConfirmBtnOfSelectProductDialog(list) {
                if (list.length) {
                    this.selectProductDialogState = false;
                    list.forEach(x => {
                        this.ruleForm.productList.push({
                            productId: x.id,
                            productCode: x.code,
                            productName: x.name,
                            productModels: x.models,
                            unitId: x.unitId,
                            unitCode: x.unitCode,
                            unitName: x.unitName
                        });
                    });
                }
            },
            onSelectBatchChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'batchId', e.id);
                    this.$set(this.ruleForm, 'batchCode', e.batchCode);
                }
            },
            onSelectProductChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'batchId', null);
                    this.$set(this.ruleForm, 'batchCode', '');
                    this.$set(this.ruleForm, 'productId', e.id);
                    this.$set(this.ruleForm, 'productCode', e.code);
                    this.$set(this.ruleForm, 'productName', e.name);
                    this.$set(this.ruleForm, 'productModels', e.models);
                }
            },
            onVisibleChangeOfCheckboxEmpDialog(e) {
                this.checkboxEmpDialogState = e;
            },
            onConfirmBtnOfCheckboxEmpDialog(arr) {
                arr.forEach(x => {
                    this.ruleForm.empList.push({
                        id: x.id,
                        code: x.code,
                        name: x.name
                    });
                });
                this.checkboxEmpDialogState = false;
            },
            onDateTimeChange(e) {
                this.$set(this.ruleForm, 'scheduleShiftId', null);
                this.$set(this.ruleForm, 'shiftName', null);
                this.$set(this.ruleForm, 'shiftId', null);
                this.$set(this.ruleForm, 'billDate', formatDate(e));
                this.getScheduleShiftForTimeRequest();
            },
            getScheduleShiftForTimeRequest() {
                if (this.ruleForm.workshopId && this.ruleForm.feedstockDateTime) {
                    return workforcemanagementScheduleShiftByTime({
                        startTime: this.ruleForm.feedstockDateTime,
                        workshopId: this.ruleForm.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res;
                            if (resData) {
                                this.$set(this.ruleForm, 'scheduleId', resData.scheduleId);
                                this.$set(this.ruleForm, 'scheduleShiftId', resData.id);
                                this.$set(this.ruleForm, 'scheduleShiftName', resData.shiftName);
                            }
                        }
                    });
                }
            },
            onPrdLineChange(e) {
                const item = this.productionLineList.find(x => x.id === e);
                this.$set(this.ruleForm, 'productionLineId', item.id);
                this.$set(this.ruleForm, 'productionLineCode', item.code);
                this.$set(this.ruleForm, 'productionLineName', item.name);
            },
            getMachineChangeDetailRequest(id) {
                return productionPrdNoticeMachineChangeGet({ id }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res;
                        resData.productionPlanLine = resData.productionPlanLine || {};

                        this.$set(this.ruleForm, 'batchId', resData.productionPlanLine.batchId);
                        this.$set(this.ruleForm, 'batchCode', resData.productionPlanLine.batchCode);

                        this.$set(this.ruleForm, 'productId', resData.productionPlanLine.productId);
                        this.$set(this.ruleForm, 'productCode', resData.productionPlanLine.productCode);
                        this.$set(this.ruleForm, 'productName', resData.productionPlanLine.productName);
                        this.$set(this.ruleForm, 'productModels', resData.productionPlanLine.productModels);

                        this.$set(this.ruleForm, 'ppfCottonBlendingId', resData.productionPlanLine.ppfCottonBlendingId);
                        this.$set(this.ruleForm, 'ppfCottonBlendingCode', resData.productionPlanLine.ppfCottonBlendingCode);
                        this.$set(this.ruleForm, 'prdNoticeId', resData.prdNotice.id);
                        this.$set(this.ruleForm, 'prdNoticeCode', resData.prdNotice.code);
                        this.getConfigCottonDetailRequest();
                    }
                });
            },
            getConfigCottonDetailRequest() {
                if (!this.ruleForm.ppfCottonBlendingId) return false;
                return cottonPpfCottonBlendingGet({ id: this.ruleForm.ppfCottonBlendingId }).then(res => {
                    if (res.data.status === 200) {
                        this.$set(this.ruleForm, 'productList', res.data.res.ppfCottonBlendingItemList);
                    }
                });
            },
            defaultRowData() {
                return {
                    name: '',
                    value: ''
                };
            },
            onRemoveBtn(scope) {
                if (this.ruleForm.productList.length > 1) {
                    this.ruleForm.productList.splice(scope.rowIndex, 1);
                }
            },
            onAddBtn(scope) {
                this.ruleForm.empList.splice(scope.rowIndex + 1, 0, this.defaultRowData());
            },
            getParamData() {
                this.$set(this.ruleForm, 'billDate', formatDate(this.ruleForm.feedstockDateTime));
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                // 新增
                if (!this.dataParams.id) {
                    this.ruleForm.id = null;
                    productionFeedstockCreate(this.getParamData()).then(res => {
                        this.saveBtnLoading = false;
                        if (res.data.status === 200) {
                            this.$tipsBar(this, 'save');
                            this.$emit('on-finish');
                        }
                    });
                    return;
                }

                // 编辑
                productionFeedstockUpdate(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return productionFeedstockGet({ id: this.dataParams.id }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getProductionLineListRequest() {
                return ppfProductionLinePage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.productionLineList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.$set(this.ruleForm, 'empList', [
                    {
                        id: this.$store.state.user.empInfo.id,
                        code: this.$store.state.user.empInfo.code,
                        name: this.$store.state.user.empInfo.name
                    }
                ]);
                this.$set(this.ruleForm, 'auditState', 1);
                this.$set(this.ruleForm, 'workshopId', this.dataParams.workshopId);
                this.$set(this.ruleForm, 'workshopCode', this.dataParams.workshopCode);
                this.$set(this.ruleForm, 'workshopName', this.dataParams.workshopName);
                this.$set(this.ruleForm, 'productionLineId', this.dataParams.productionLineId);
                this.$set(this.ruleForm, 'productionLineCode', this.dataParams.productionLineCode);
                this.$set(this.ruleForm, 'productionLineName', this.dataParams.productionLineName);
                this.$set(this.ruleForm, 'billDate', this.dataParams.belongDate);
                this.$set(this.ruleForm, 'feedstockDateTime', `${this.dataParams.belongDate} ${formatTime(Date.now()).split(' ')[1]}`);
                await this.getProductionLineListRequest();
                if (this.dataParams.id) await this.getDetailRequest();
                await this.getScheduleShiftForTimeRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
